package com.lanou.dllo.soccernews.utils;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Vibrator;

/**
 * Created by dllo on 15/10/27.
 */
public class ShakeUtils implements SensorEventListener {
    private SensorManager mSensorManager= null;
    private OnShakeListener onShakeListener =null;
    private static final int SENSOR_VALUE = 14;
    private Vibrator vibrator;
    // private

    public ShakeUtils(Context context) {
        //1获得硬件信息
        mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
        vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
    }

    public void setOnShakeListener(OnShakeListener onShakeListener) {
        this.onShakeListener = onShakeListener;
    }

    public void onResume(){
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(
                Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_NORMAL);
    }

    public void onPause(){
        mSensorManager.unregisterListener(this);
    }

    public interface OnShakeListener {
        public void onShake();
       // public void stop();
        //public void start();
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
            int sensorType = event.sensor.getType();
        float[] values = event.values;
        if (sensorType == Sensor.TYPE_ACCELEROMETER){
            //这里可以调节摇一摇的灵敏度
            if ((Math.abs(values[0]) > SENSOR_VALUE || Math.abs(values[1]) > SENSOR_VALUE
                    || Math.abs(values[2]) > SENSOR_VALUE)){
                vibrator.vibrate(200);
                if( null != onShakeListener ){
                    onShakeListener.onShake();
                }
            }
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

}

